package com.example.demo;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.SessionAttribute;

@RequestMapping("/session")
@RestController
public class GetSession {
    @RequestMapping("/set")
    public String setSession(HttpServletRequest request){
        HttpSession session = request.getSession();
        session.setAttribute("name","李宗伟");
        session.setAttribute("age",22);
        return "session设置成功";
    }

    @RequestMapping("/get")
    public String getSession(HttpServletRequest request){
        HttpSession session = request.getSession(false);
        if (session == null ){
            return "用户未登录";
        }else{
            String name = (String)session.getAttribute("name");
            return "登录用户为："+ name;
        }
    }

    @RequestMapping("/get2")
    public String get2(HttpSession session){
        String name = (String)session.getAttribute("name");
        return "登录用户为："+ name;

    }

    @RequestMapping("/get3")
    public String get3(@SessionAttribute("name") String name){
        return "登录用户为："+ name;
    }
}
